package net.qhzw.geologr5.gis.service.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import net.qhzw.geologr5.gis.api.system.entity.User;
import net.qhzw.geologr5.gis.common.framework.utils.JsonResult;
import net.qhzw.geologr5.gis.common.framework.utils.StringUtils;
import net.qhzw.geologr5.gis.common.security.utils.SecurityUtils;
import net.qhzw.geologr5.gis.service.system.component.ApplyBorrowingLst;
import net.qhzw.geologr5.gis.service.system.component.FileTemplate;
import net.qhzw.geologr5.gis.service.system.dto.BorrowDto;
import net.qhzw.geologr5.gis.service.system.entity.Borrow;
import net.qhzw.geologr5.gis.service.system.entity.BorrowDetails;
import net.qhzw.geologr5.gis.service.system.entity.ProjectData;
import net.qhzw.geologr5.gis.service.system.mapper.*;
import net.qhzw.geologr5.gis.service.system.model.BodyParam;
import net.qhzw.geologr5.gis.service.system.model.HeaderParam;
import net.qhzw.geologr5.gis.service.system.query.BorrowQuery;
import net.qhzw.geologr5.gis.service.system.service.BorrowService;
import net.qhzw.geologr5.gis.service.system.utils.StringUtil;
import net.qhzw.geologr5.gis.service.system.utils.UUIDUtil;
import net.qhzw.geologr5.gis.service.system.vo.project.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/***
 * 借阅管理
 */
@Service
@Slf4j
@Component
public class BorrowServiceImpl implements BorrowService {


    @Autowired
    private BorrowMapper borrowMapper;

    @Autowired
    private BorrowDetailsMapper borrowDetailsMapper;

    @Autowired
    private FileTemplate fileTemplate;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ApplyBorrowingLst applyBorrowingLst;

    @Autowired
    private ProjectDataMapper projectDataMapper;

    @Autowired
    private ProjectMapMapper projectMapMapper;


    @Value("${addressDoc}")
    private String addressDoc;


    @Value("${file.projectDate.accsPathPrfx}")
    private String accsPathPrfx;

    /***
     * 借阅审核
     * @param query
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult audit(BorrowQuery query) {
        log.info("借阅审核==BorrowServiceImpl==method:audit==param: {}", JSON.toJSONString(query));
        try {

            BorrowDto borrowDto = borrowMapper.selectById(query.getId());
            if (borrowDto == null) {
                return JsonResult.error("id不存在");
            }
            if (!(borrowDto.getOperation() == 2)) {
                return JsonResult.error("先完成线下操作");
            }
            //审批(0:不通过,1:通过)
            borrowDto.setAudit(1);
            borrowDto.setEntData(query.getEntData());
            borrowDto.setDownloadCount(query.getDownloadCount());
            borrowDto.setOperation(3);
            borrowMapper.updateById(borrowDto);
            QueryWrapper<BorrowDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("borrow_id", query.getId());
            List<BorrowDetails> borrowDetails = borrowDetailsMapper.selectList(queryWrapper);
            for (BorrowDetails borrowDetail : borrowDetails) {
                borrowDetail.setEndDate(query.getEntData());
                borrowDetail.setMaxCount(query.getDownloadCount());
                borrowDetailsMapper.updateById(borrowDetail);
            }

            return JsonResult.success();
        } catch (Exception e) {
            log.info("借阅审核失败==BorrowServiceImpl==method:audit==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }


    /***
     * 借阅查询
     * @param query
     * @return
     */
    @Override
    public JsonResult findBorrow(BorrowQuery query) {
        Map<String, Object> result = new HashMap<>();
        PageHelper.startPage(query.getPage(), query.getLimit());
        try {
            List<BorrowVo> borrowDtoList = borrowMapper.selectBorrow(query);
            PageInfo<BorrowVo> pageInfo = new PageInfo<>(borrowDtoList);
            result.put("list", pageInfo.getList());
            result.put("total", pageInfo.getTotal());
            return JsonResult.success(result);
        } catch (Exception e) {
            return JsonResult.error(e.getMessage());
        }

    }


    /***
     * 借阅单下载
     * @param id
     * @return
     */
    @Override
    public JsonResult print(String id) {
        log.info("打印借阅审核==BorrowServiceImpl==method:print==param: {}", id);
        try {


            QueryWrapper<BorrowDetails> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("borrow_id", id);
            List<BorrowDetails> borrowDetails = borrowDetailsMapper.selectList(queryWrapper);
            List<Integer> dataIds = new ArrayList<>();
            List<Integer> mapIds = new ArrayList<>();
            for (BorrowDetails borrowDetail : borrowDetails) {
                if (borrowDetail.getFileId() != null) {
                    dataIds.add(borrowDetail.getFileId());
                }
                if (borrowDetail.getMapId() != null) {
                    mapIds.add(borrowDetail.getMapId());
                }
            }
            List<ProjectDataVo> projectDataList = new ArrayList<>();
            if (dataIds != null && !dataIds.isEmpty()) {
                projectDataList = projectDataMapper.projectInfoByIdList(dataIds);
            }
            List<ProjectMapVo> projectMapList = new ArrayList<>();
            if (mapIds != null && !mapIds.isEmpty()) {
                projectMapList = projectMapMapper.selectProjectMapByIdList(mapIds);
            }

            List<BodyParam> bodys = new ArrayList();
            for (ProjectDataVo projectData : projectDataList) {
                BodyParam bodyParam = new BodyParam();
                bodyParam.setFilename(projectData.getFileName());
                bodyParam.setLevel(projectData.getAuthorityName());
                bodys.add(bodyParam);
            }
            for (ProjectMapVo projectMapVo : projectMapList) {
                BodyParam bodyParam = new BodyParam();
                bodyParam.setFilename(projectMapVo.getMapName());
                bodyParam.setLevel(projectMapVo.getAuthorityName());
                bodys.add(bodyParam);
            }
            BorrowDto borrowDto = borrowMapper.selectById(id);
            borrowDto.setOperation(1);
            HeaderParam header = new HeaderParam();
            header.setApplyNo(borrowDto.getBorroNo());
            header.setApplyDate(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));

            String filename = addressDoc + UUIDUtil.getRandomString(8) + ".doc";

            //借阅人权限
            if (borrowDto.getUserId() == null || borrowDto.getUserId() <= 0) {
                return JsonResult.error("获取不到申请资源用户的用户的信息");
            }
            User user = userMapper.selectById(borrowDto.getUserId());
            if (user == null) {
                return JsonResult.error("获取不到申请资源用户的用户的信息");
            }
            if (user.getIdentity() == null) {
                return JsonResult.error("用户权限无法识别");
            }

            //身份权限（1：对内，2：对外）
            if (user.getIdentity() == 1) {
                String filePath = applyBorrowingLst.exportAnnualReport(header, bodys, "1", filename);
                borrowMapper.updateById(borrowDto);
                return JsonResult.success(filePath, "SUCCESS");
            } else if (user.getIdentity() == 1) {
                String filePath = applyBorrowingLst.exportAnnualReport(header, bodys, "2", filename);
                borrowMapper.updateById(borrowDto);
                return JsonResult.success(filePath, "SUCCESS");
            }
            return JsonResult.error("生成借阅单失败,请刷新页面");
        } catch (Exception e) {
            log.error("打印借阅审核失败==BorrowServiceImpl==method:print==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }

    }


    /***
     * 借阅审核单上传
     * @param file
     * @return
     */
    @Override
    public JsonResult upload(MultipartFile file, BorrowQuery query) {
        log.info("借阅审核单上传==BorrowServiceImpl==method:upload==param fileName: {}", file.getOriginalFilename());
        try {
            BorrowDto borrowDto = borrowMapper.selectById(query.getId());
            if (borrowDto == null) {
                return JsonResult.error("查询有误");
            }
            //上传文件
            String path = fileTemplate.fileUpload(file);
            if (StringUtils.isEmpty(path)) {
                return JsonResult.error("上传失败");
            }
            borrowDto.setBorrowUrl(path);
            borrowDto.setOperation(2);
            borrowMapper.updateById(borrowDto);
            return JsonResult.success();
        } catch (Exception e) {
            log.error("借阅审核单上传失败==BorrowServiceImpl==method:upload==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }


    /***
     * 借阅审核单下载
     * @return
     */
    @Override
    public JsonResult download(HttpServletResponse response, String id) {
        try {
            Borrow borrow = borrowMapper.selectBorrowById(id);
            if (borrow == null) {
                return JsonResult.error("id不存在");
            }
            if (borrow.getBorrowUrl() == null || borrow.getBorrowUrl().length() <= 0) {
                return JsonResult.error("文件不存在");
            }
            return JsonResult.success(borrow.getBorrowUrl(), "success");
        } catch (Exception e) {
            return JsonResult.error();
        }
    }


    /****
     * 申请文件目录
     * @param id
     * @return
     */
    @Override
    public JsonResult findBorrowDetails(String id) {
        log.info("申请文件目录==BorrowServiceImpl==method:findBorrowDetails==param: {}", id);
        try {
            List<BorrowDetailsVo> borrowDetailsList = borrowDetailsMapper.selecBorrowDetails(id);
            for (BorrowDetailsVo borrowDetailsVo : borrowDetailsList) {
                if (borrowDetailsVo.getFileId() != null && borrowDetailsVo.getFileId() > 0) {
                    MapQueryResult queryResult = borrowDetailsMapper.selectMapQueryResult(borrowDetailsVo.getFileId(), "projectData");
                    if (queryResult != null && !StringUtils.isEmpty(queryResult.getName())) {
                        borrowDetailsVo.setFilename(queryResult.getName());
                    }
                }
                if (borrowDetailsVo.getMapId() != null && borrowDetailsVo.getMapId() > 0) {
                    MapQueryResult queryResult = borrowDetailsMapper.selectMapQueryResult(borrowDetailsVo.getMapId(), "projectMap");
                    if (queryResult != null && !StringUtils.isEmpty(queryResult.getName())) {
                        borrowDetailsVo.setFilename(queryResult.getName());
                    }
                }
            }
            return JsonResult.success(borrowDetailsList, "SUCCESS");
        } catch (Exception e) {
            log.error("申请文件目录失败==BorrowServiceImpl==method:findBorrowDetails==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }


    /***
     * 申请文件目录 下载
     * @param id
     * @return
     */
    @Override
    public JsonResult appFileCtlgDownload(Integer id) {
        log.info("申请文件目录下载==BorrowServiceImpl==method:appFileCtlgDownload==param: {}", id);
        try {
            BorrowDetails borrowDetails = borrowDetailsMapper.selectById(id);
            if (borrowDetails == null) {
                return JsonResult.error("当前数据无记录");
            }

            //判断下载截止时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date endDate = borrowDetails.getEndDate();
            Date newDate = new Date();
            String dateTime1 = dateFormat.format(endDate).replace("-", "");
            String dateTime2 = dateFormat.format(newDate).replace("-", "");
            if (Integer.parseInt(dateTime1) < Integer.parseInt(dateTime2)) {
                return JsonResult.error("下载日期已截止");
            }


            if (borrowDetails.getNowCount() == null) {
                borrowDetails.setNowCount(0);
            }
            if (borrowDetails.getMaxCount() == null || borrowDetails.getMaxCount() < 0 || borrowDetails.getMaxCount() <= borrowDetails.getNowCount()) {
                return JsonResult.error("下载次数超限");
            }

            if (borrowDetails.getMapId() != null && borrowDetails.getMapId() > 0) {
                net.qhzw.geologr5.gis.service.system.entity.ProjectMap projectMap = projectMapMapper.selectById(borrowDetails.getMapId());
                if (!StringUtils.isEmpty(projectMap.getArsgist())) {
                    borrowDetails.setNowCount(borrowDetails.getNowCount() + 1);
                    borrowDetailsMapper.updateById(borrowDetails);
                    return JsonResult.success(projectMap.getArsgist(), "SUCCESS");
                }
            }

            if (borrowDetails.getFileId() != null && borrowDetails.getFileId() > 0) {
                ProjectData projectData = projectDataMapper.selectById(borrowDetails.getFileId());
                if (!StringUtils.isEmpty(projectData.getFileUrl())) {
                    borrowDetails.setNowCount(borrowDetails.getNowCount() + 1);
                    borrowDetailsMapper.updateById(borrowDetails);
                    return JsonResult.success(accsPathPrfx + projectData.getFileUrl(), "SUCCESS");
                }
            }
            return JsonResult.error();
        } catch (Exception e) {
            log.error("申请文件目录下载失败==BorrowServiceImpl==method:appFileCtlgDownload==errMsg: {}", e.getMessage());
            return JsonResult.error(e.getMessage());
        }
    }


}
